package lanou.a36ke_01.fragmengs.newsfragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import lanou.a36ke_01.activity.newsactivity.NewsChildActivity;
import lanou.a36ke_01.activity.newsactivity.SearchActivity;
import lanou.a36ke_01.adapters.newsadapter.NewsAdapter;
import lanou.a36ke_01.adapters.newsadapter.NewsViewPagerAdapter;
import lanou.a36ke_01.adapters.newsadapter.VieoTvAdapter;
import lanou.a36ke_01.beanlists.newsbean.NewsBean;
import lanou.a36ke_01.beanlists.newsbean.VieoTvBean;
import lanou.a36ke_01.beanlists.publicbean.UrlBean;
import lanou.a36ke_01.beanlists.publicbean.RollBean;
import lanou.a36ke_01.R;
import lanou.a36ke_01.activity.MainActivity;
import lanou.a36ke_01.tools.BaseFragment;
import lanou.a36ke_01.tools.MyApp;
import lanou.a36ke_01.activity.newsactivity.newstool.MySwipeRefreshLayout;
import lanou.a36ke_01.tools.NetTool;


public class NewsFragment extends BaseFragment implements View.OnClickListener {

    private String url = "https://rong.36kr.com/api/mobi/news?pageSize=";
    private String urlTwo = "&columnId=all&pagingAction=up";
    private String urlTv = "https://rong.36kr.com/api/mobi/news?pageSize=20&columnId=tv&pagingAction=up";
    private ListView listView;
    int page = 1;
    private String all;
    private NewsAdapter adapter;
    private ViewPager pager;
    private NewsViewPagerAdapter pagerAdapter;
    private BatteryReceiver mReceiver;
    private View view;
    private ArrayList<String> arrayList;
    private MySwipeRefreshLayout mySwipeRefreshLayout;
    private TextView newsTitleTv;


    @Override
    protected int setLayout() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {
        newsTitleTv = bindView(R.id.newsTitleTv);
        listView = bindView(R.id.news_list_view);
        adapter = new NewsAdapter(getContext());
        //头布局的适配器
        pagerAdapter = new NewsViewPagerAdapter(MyApp.getContext());
        //设置头布局
        view = LayoutInflater.from(getContext()).inflate(R.layout.news_item_taketurn, listView, false);
        pager = (ViewPager) view.findViewById(R.id.news_fragment_taketurn_pager);
        listView.addHeaderView(view);
        ImageView imageView = bindView(R.id.iv_news_chouti);
        //点开抽屉的imageview
        imageView.setOnClickListener(this);
        //找到下拉刷新 下拉加载的id
        mySwipeRefreshLayout = bindView(R.id.news_fragment_my_srl);
        //设置刷新时 显示的颜色
        mySwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_light);

        //从Adapter中调用从网络获取的图片 直接显示从网络获取会有变化
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), NewsChildActivity.class);
                //通过FeedId的不同来区分显示的内容不同
                //position - listView.getHeaderViewsCount()) 为去掉头布局的位置
                intent.putExtra("newsFeelId", adapter.getItem(position - listView.getHeaderViewsCount()).getFeedId());
                startActivity(intent);
            }
        });
        //找到搜索的id
        ImageView search = bindView(R.id.news_fragment_search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
    }


    @Override
    protected void initData() {
        initJson();
        initReLo();
        arrayList = new ArrayList<>();
        //解析轮播图片
        final NetTool netToolr = new NetTool();
        final String stringUrl = "https://rong.36kr.com/api/mobi/roundpics/v4";
        netToolr.getNetData(stringUrl, RollBean.class, new NetTool.NetListener<RollBean>() {
            @Override
            public void onSuccess(final RollBean rollBean) {
                //把图片的网址放到一个集合里 然后Adapter调用
                for (int i = 0; i < rollBean.getData().getPics().size(); i++) {
                    arrayList.add(rollBean.getData().getPics().get(i).getImgUrl());
                }
                pagerAdapter.setArrayList(arrayList);
                pagerAdapter.setViewPager(pager);
                pager.setAdapter(pagerAdapter);
                //设置item的个数
                pager.setCurrentItem(3000, false);

            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(mContext, "图片获取失败", Toast.LENGTH_SHORT).show();
            }
        });


    }

    //上拉刷新下拉加载
    protected void initReLo() {
        //下拉刷新的方法
        mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //清空ListView里面的全部数据
                listView.setAdapter(null);

                initJson();
            }
        });
        //上拉加载的方法
        mySwipeRefreshLayout.setOnLoadListener(new MySwipeRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                page++;
                Toast.makeText(mContext, "正在加载", Toast.LENGTH_SHORT).show();
                NetTool netTool = new NetTool();
                netTool.getNetData(url + (page * 20) + urlTwo, NewsBean.class, new NetTool.NetListener<NewsBean>() {
                    @Override
                    public void onSuccess(NewsBean newsBean) {
                        Log.d("NewsFragment", "newsBean.getData().getData().size():" + newsBean.getData().getData().size());
                        adapter.setNewsBean(newsBean);
                        // listView.setAdapter(adapter);
                        //停止刷新
                        mySwipeRefreshLayout.setLoading(false);
                    }

                    @Override
                    public void onError(String errorMsg) {
                    }
                });
            }
        });
    }

    // 轮播图的线程
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            pager.setCurrentItem(pager.getCurrentItem() + 1);
            Message message = handler.obtainMessage();
            message.what = 1;
            handler.sendMessageDelayed(message, 5000);
            return false;
        }
    });

    // 生命周期 onStart 当Activity开始的时候 执行这个方法
    @Override
    public void onStart() {
        super.onStart();
        Message message = handler.obtainMessage();
        message.what = 1;
        handler.sendMessageDelayed(message, 5000);
        mReceiver = new BatteryReceiver();
        //广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("lanou.36ke_01");
        getContext().registerReceiver(mReceiver, filter);
    }

    //当划出这个页面的时候就停掉
    @Override
    public void onStop() {
        super.onStop();
        handler.removeMessages(1);
        //解除广播
        getContext().unregisterReceiver(mReceiver);
    }

    @Override
    public void onClick(View v) {
        MainActivity mainActivity = (MainActivity) getActivity();
        //调用点击事件
        mainActivity.Onclicker();


    }

    //动态广播接收器
    public class BatteryReceiver extends BroadcastReceiver {


        //判断是否去掉头布局
        private boolean head = false;
        private VieoTvAdapter tvAdapter;

        @Override
        public void onReceive(Context context, Intent intent) {

            all = intent.getStringExtra("key");
            // 将抽屉的网址传到 newsAdapter里
            adapter.setUrl(all);
            if (urlTv.equals(all)){
                Toast.makeText(context, "121", Toast.LENGTH_SHORT).show();
                final NetTool netTool = new NetTool();
                netTool.getNetData(urlTv, VieoTvBean.class, new NetTool.NetListener<VieoTvBean>() {
                    @Override
                    public void onSuccess(VieoTvBean vieoTvBean) {
                        tvAdapter = new VieoTvAdapter(getContext());
                        tvAdapter.setVieoTvBean(vieoTvBean);
                        listView.removeHeaderView(view);
                        listView.setAdapter(tvAdapter);
                    }

                    @Override
                    public void onError(String errorMsg) {

                    }
                });

            } else {
                NetTool netTool = new NetTool();
                netTool.getNetData(all, NewsBean.class, new NetTool.NetListener<NewsBean>() {
                    @Override
                    public void onSuccess(NewsBean newsBean) {

                        adapter.setNewsBean(newsBean);
                        if (all.equals("https://rong.36kr.com/api/mobi/news?pageSize=20&columnId=all&pagingAction=up")) {
                            if (head == true) {
                                listView.addHeaderView(view);
                                head = false;
                            }
                        } else {
                            listView.removeHeaderView(view);
                            head = true;
                        }
                        listView.setAdapter(adapter);
                    }
                    @Override
                    public void onError(String errorMsg) {
                    }
                });
                if (UrlBean.NEWS_ALL_URL.equals(all)) {
                    newsTitleTv.setText("全部");
                } else if ((UrlBean.NEWS_EPROJECT_URL).equals(all)) {
                    newsTitleTv.setText("早期项目");
                } else if (all.equals(UrlBean.NEWS_BWHEEL_URL)) {
                    newsTitleTv.setText("B轮后");
                } else if (all.equals(UrlBean.NEWS_BCOMPANY_URL)) {
                    newsTitleTv.setText("大公司");
                } else if (all.equals(UrlBean.NEWS_CAPITAL_URL)) {
                    newsTitleTv.setText("资本");
                } else if (all.equals(UrlBean.NEWS_DEPTH_URL)) {
                    newsTitleTv.setText("深度");
                } else if (all.equals(UrlBean.NEWS_STUDY_URL)) {
                    newsTitleTv.setText("研究");
                } else {
                    newsTitleTv.setText("氪KV");
                }
            }
        }
    }
    //解析数据
    protected void initJson() {
        NetTool netTool = new NetTool();
        netTool.getNetData(url + (page * 20) + urlTwo, NewsBean.class, new NetTool.NetListener<NewsBean>() {
            @Override
            public void onSuccess(NewsBean newsBean) {
                adapter.setNewsBean(newsBean);
                listView.setAdapter(adapter);
                mySwipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }
}

//弹栈 pop  standard singleTop singleTask singleInstance
//压栈
//singleTask 只有一个Activity
//onNewIntent 是一个生命周期 当一个Activity不会走onCreate 方法 singleTask的形式 就不会启动新的Activity 但是Intent是新的
//然后走onNewIntent 方法 接收到一个新的值
//可惜时光河流冲散你我 离别时连背影都觉淡漠


